<template>
  <view class="history-container">
    <!-- 日期筛选区域 -->
    <view class="date-filter">
      <picker mode="date" :value="startDate" @change="onStartDateChange">
        <view class="date-item">
          <text class="label">开始日期</text>
          <text class="date-text">{{ startDate || "请选择" }}</text>
        </view>
      </picker>

      <picker mode="date" :value="endDate" @change="onEndDateChange">
        <view class="date-item">
          <text class="label">结束日期</text>
          <text class="date-text">{{ endDate || "请选择" }}</text>
        </view>
      </picker>
    </view>

    <!-- 历史记录列表 -->
    <view class="history-list">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-wrapper">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else-if="historyList.length === 0" class="empty-wrapper">
        <text class="empty-text">暂无数据</text>
      </view>

      <!-- 历史记录列表 -->
      <view
        v-else
        class="history-item"
        v-for="(item, index) in historyList"
        :key="index"
      >
        <view class="batch-header">
          <view class="left-info">
            <view class="date-time">
              <text class="date">{{ item.date }}</text>
              <text class="time">{{ item.time }}</text>
            </view>
          </view>
          <view class="right-info">
            <view class="amount-info">
              <text class="label">发放数量: </text>
              <text
                class="amount"
                :style="{ color: getAmountColor(item.amount) }"
                >{{ item.amount }}</text
              >
            </view>
            <view class="user-info">
              <image
                class="avatar"
                :src="item.avatar"
                mode="aspectFill"
              ></image>
              <view class="user-detail">
                <text class="name">{{ item.name }}</text>
                <text class="id">ID: {{ item.recipient_id }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 领取情况统计 -->
        <view class="receive-stats">
          <view class="stat-item">
            <text class="stat-label">已领取:</text>
            <text class="stat-value received">{{ item.received_count }}</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">待领取:</text>
            <text class="stat-value pending">{{ item.pending_count }}</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">已撤销:</text>
            <text class="stat-value cancelled">{{
              getCancelledCount(item.gift_details)
            }}</text>
          </view>
        </view>

        <!-- 礼包详情列表 -->
        <view
          class="gift-details"
          v-if="item.gift_details && item.gift_details.length > 0"
        >
          <view
            class="gift-detail-item"
            v-for="(gift, giftIndex) in item.gift_details"
            :key="giftIndex"
          >
            <view class="gift-info">
              <view class="gift-status">
                <view
                  class="status-tag"
                  :class="{
                    received: gift.status === 1,
                    pending: gift.status === 0,
                    cancelled: gift.status === 2,
                  }"
                >
                  {{ getStatusText(gift.status) }}
                </view>
                <text class="gift-amount">{{ gift.amount }}包沐浴露</text>
              </view>

              <view
                class="gift-receiver"
                v-if="gift.status === 1 && gift.receiver"
              >
                <image
                  class="receiver-avatar"
                  :src="gift.receiver.avatar"
                  mode="aspectFill"
                ></image>
                <text class="receiver-name"
                  >{{ gift.receiver.nickname }} (ID:
                  {{ gift.receiver.uid }})</text
                >
                <text class="receive-date">{{
                  formatReceiveDate(gift.receive_date)
                }}</text>
              </view>
            </view>

            <!-- 撤销按钮 -->
            <view class="gift-actions" v-if="gift.status === 0">
              <view class="cancel-btn" @tap="handleCancelGift(gift.id)">
                <uni-icons type="close" size="14" color="#ff4757"></uni-icons>
                <text class="cancel-text">撤销</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { getSendHistory, cancelGift } from "../../api/gift";

// 声明 uni 对象
declare const uni: any;

// 历史记录项类型
interface GiftDetail {
  id: number;
  status: number;
  amount: number;
  receive_date: number | null;
  created_at: number;
  receiver?: {
    uid: number;
    nickname: string;
    avatar: string;
  };
}

interface HistoryItem {
  id: number;
  date: string;
  time: string;
  amount: number;
  name: string;
  recipient_id: number;
  avatar: string;
  gift_count: number;
  gift_per_count: number;
  received_count: number;
  pending_count: number;
  gift_details: GiftDetail[];
}

const startDate = ref("");
const endDate = ref("");
const historyList = ref<HistoryItem[]>([]);
const loading = ref(false);

// 获取历史记录
const getHistoryList = async () => {
  try {
    loading.value = true;
    const params: any = {};
    if (startDate.value) params.start_date = startDate.value;
    if (endDate.value) params.end_date = endDate.value;
    const res = await getSendHistory(params);
    if (res.result === 1 && Array.isArray(res.data)) {
      // 兜底处理时间
      historyList.value = res.data.map((item: any) => {
        // 如果没有date和time，尝试用created_at格式化，否则显示--
        if (
          !item.date ||
          item.date === false ||
          !item.time ||
          item.time === false
        ) {
          if (item.created_at) {
            const d = new Date(item.created_at * 1000);

            item.date = `${String(d.getMonth() + 1).padStart(2, "0")}-${String(
              d.getDate()
            ).padStart(2, "0")}`;
            item.time = `${String(d.getHours()).padStart(2, "0")}:${String(
              d.getMinutes()
            ).padStart(2, "0")}`;
          } else {
            item.date = "--";
            item.time = "--";
          }
        }
        return item;
      });
    } else {
      uni.showToast({
        title: res.msg || "获取数据失败",
        icon: "none",
      });
      historyList.value = [];
    }
  } catch (error) {
    uni.showToast({
      title: "网络错误",
      icon: "none",
    });
    historyList.value = [];
  } finally {
    loading.value = false;
  }
};

// 撤销礼包
const handleCancelGift = async (giftId: number) => {
  try {
    uni.showModal({
      title: "确认撤销",
      content: "确定要撤销这个礼包吗？撤销后无法恢复。",
      success: async (res: any) => {
        if (res.confirm) {
          uni.showLoading({ title: "撤销中..." });
          const result = await cancelGift({ gift_id: giftId });
          if (result.result === 1) {
            uni.showToast({ title: "撤销成功", icon: "success" });
            getHistoryList(); // 重新加载数据
          } else {
            uni.showToast({ title: result.msg || "撤销失败", icon: "none" });
          }
          uni.hideLoading();
        }
      },
    });
  } catch (error) {
    uni.showToast({ title: "网络错误", icon: "none" });
  }
};

// 格式化领取日期
const formatReceiveDate = (timestamp: number | null) => {
  if (!timestamp) return "";
  const date = new Date(timestamp * 1000);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")} ${String(
    date.getHours()
  ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
};

const onStartDateChange = (e: any) => {
  startDate.value = e.detail.value;
  getHistoryList();
};

const onEndDateChange = (e: any) => {
  endDate.value = e.detail.value;
  getHistoryList();
};

onMounted(() => {
  getHistoryList();
});

const getAmountColor = (amount: number) => {
  if (amount >= 1000) return "#00A971";
  if (amount >= 500) return "#2B85E4";
  return "#5C6B77";
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return "待领取";
    case 1:
      return "已领取";
    case 2:
      return "已撤销";
    default:
      return "未知状态";
  }
};

// 获取撤销数量
const getCancelledCount = (giftDetails: GiftDetail[]) => {
  return giftDetails.filter((gift) => gift.status === 2).length;
};
</script>

<style lang="scss" scoped>
.history-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.date-filter {
  display: flex;
  justify-content: space-between;
  padding: 30rpx;
  background: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;

  .date-item {
    display: flex;
    align-items: center;
    cursor: pointer;

    .label {
      font-size: 28rpx;
      color: #333333;
      margin: 0 20rpx;
    }

    .date-text {
      font-size: 28rpx;
      color: #666666;
    }
  }
}

.history-list {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 0 30rpx;

  .loading-wrapper,
  .empty-wrapper {
    padding: 80rpx 0;
    text-align: center;

    .loading-text,
    .empty-text {
      font-size: 28rpx;
      color: #999999;
    }
  }

  .history-item {
    padding: 30rpx 0;
    border-bottom: 1px solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .batch-header {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      .left-info {
        margin-right: 30rpx;
        min-width: 120rpx;
        display: flex;
        align-items: center;

        .date-time {
          display: flex;
          flex-direction: column;
          align-items: center;

          .date {
            font-size: 28rpx;
            color: #333333;
            margin-bottom: 8rpx;
          }

          .time {
            font-size: 24rpx;
            color: #999999;
          }
        }
      }

      .right-info {
        flex: 1;

        .amount-info {
          margin-bottom: 16rpx;

          .label {
            font-size: 28rpx;
            color: #333333;
          }

          .amount {
            font-size: 32rpx;
            font-weight: bold;
          }
        }

        .user-info {
          display: flex;
          align-items: center;

          .avatar {
            width: 64rpx;
            height: 64rpx;
            border-radius: 32rpx;
            margin-right: 16rpx;
          }

          .user-detail {
            .name {
              font-size: 28rpx;
              color: #333333;
              margin-bottom: 4rpx;
              display: block;
            }

            .id {
              font-size: 24rpx;
              color: #999999;
            }
          }
        }
      }
    }

    .receive-stats {
      display: flex;
      margin-bottom: 20rpx;
      padding: 20rpx;
      background: #f8f9fa;
      border-radius: 12rpx;

      .stat-item {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;

        .stat-label {
          font-size: 26rpx;
          color: #666666;
          margin-right: 8rpx;
        }

        .stat-value {
          font-size: 28rpx;
          font-weight: bold;

          &.received {
            color: #00a971;
          }

          &.pending {
            color: #ff6b35;
          }

          &.cancelled {
            color: #999999;
          }
        }
      }
    }

    .gift-details {
      .gift-detail-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        margin-bottom: 16rpx;
        background: #f8f9fa;
        border-radius: 12rpx;

        .gift-info {
          flex: 1;

          .gift-status {
            display: flex;
            align-items: center;
            margin-bottom: 12rpx;

            .status-tag {
              font-size: 22rpx;
              padding: 6rpx 12rpx;
              border-radius: 6rpx;
              margin-right: 16rpx;

              &.pending {
                background: rgba(255, 107, 53, 0.1);
                color: #ff6b35;
              }

              &.received {
                background: rgba(0, 169, 113, 0.1);
                color: #00a971;
              }

              &.cancelled {
                background: rgba(153, 153, 153, 0.1);
                color: #999999;
              }
            }

            .gift-amount {
              font-size: 26rpx;
              color: #333333;
              font-weight: 500;
            }
          }

          .gift-receiver {
            display: flex;
            align-items: center;
            flex-wrap: wrap;

            .receiver-avatar {
              width: 40rpx;
              height: 40rpx;
              border-radius: 20rpx;
              margin-right: 12rpx;
            }

            .receiver-name {
              font-size: 24rpx;
              color: #666666;
              margin-right: 16rpx;
            }

            .receive-date {
              font-size: 22rpx;
              color: #999999;
            }
          }
        }

        .gift-actions {
          .cancel-btn {
            display: flex;
            align-items: center;
            padding: 12rpx 20rpx;
            background: #ffffff;
            border: 2rpx solid #ff4757;
            border-radius: 24rpx;
            color: #ff4757;
            font-size: 24rpx;
            cursor: pointer;

            .cancel-text {
              margin-left: 6rpx;
              color: #ff4757;
            }
          }
        }
      }
    }
  }
}
</style>
